<?php

use App\Utils\Common;

class ThemeController extends \App\Http\Controllers\Controller
{
    public function index(\Illuminate\Http\Request $request)
    {
        $settings = (new \App\Db\Setting())->getSettingDir($request->siteId);
        $themeJson = json_decode($settings["theme_json_{$settings['theme']}"], true);
        $archives = $this->archive($request, true);
        foreach ($archives['posts'] as &$v) {
            $v->thumb = strip_tags(htmlspecialchars_decode($v->content_html));
            $dotTail = mb_strlen($v->thumb) >= 50;
            $v->thumb = mb_substr($v->thumb, 0, 50) . ($dotTail ? '...' : '');
        }
        $pageData = [
            'title' => $settings['title'] ?? '',
            'nav' => json_decode($settings['nav']) ?? [],
            'footer' => $settings['footer'],
            'logo' => $settings['logo'],
            'subTitle' => $settings['subTitle'],
            'j' => $themeJson,
            'archives' => $archives
        ];
        if (Common::isMobile()) {
            return view('pages.index_mobile', $pageData);
        } else {
            return view('pages.index', $pageData);
        }
    }

    public function archive(\Illuminate\Http\Request $request, $returnData = false)
    {
        $settings = (new \App\Db\Setting())->getSettingDir($request->siteId);

        $db = \Illuminate\Support\Facades\DB::table('blog')->where([
            'is_del' => 0,
            'site' => $request->siteId
        ]);
        if ($request->input('category') && $request->input('category') > 0) {
            $db = $db->where(['category' => $request->input('category')]);
        }
        $count = $db->count();
        if ($settings['blogUsePage'] == 1 && $settings['blogPageLimit'] > 0) {
            $limit = $settings['blogPageLimit'];
            $page = $request->input('page', 1);
            $db = $db->skip(($page - 1) * $limit)->limit($limit);
        }
        $res = $db->orderByDesc('create_time')->get();
        $categorys = array_column(\Illuminate\Support\Facades\DB::table('category')->whereIn('id', array_column($res->toArray(), 'category'))->get()->toArray(), null, 'id');
        foreach ($res as &$v) {
            $v->category_name = isset($v->category) && isset($categorys[$v->category]) ? $categorys[$v->category]->name : '';
        }
        $resData = [
            'logo' => $settings['logo'],
            'title' => $settings['title'],
            'subTitle' => $settings['subTitle'],
            'nav' => json_decode($settings['nav']) ?? [],
            'footer' => $settings['footer'],
            'posts' => $res,
            'blogUsePage' => $settings['blogUsePage'],
            'blogPageLimit' => $settings['blogPageLimit'],
            'page' => $page ?? false,
            'count' => $count ?? 0,
            'archiveOpenBlogInNewTab' => $settings['archiveOpenBlogInNewTab'],
            'category' => $request->input('category', '')
        ];
        return $returnData ? $resData : view('pages.archive', $resData);
    }

    public function post($id, \Illuminate\Http\Request $request)
    {
        $settings = (new \App\Db\Setting())->getSettingDir($request->siteId);
        $settingArr = [
            'logo' => $settings['logo'],
            'title' => $settings['title'],
            'subTitle' => $settings['subTitle'],
            'nav' => json_decode($settings['nav']) ?? [],
            'footer' => $settings['footer']
        ];
        if (!$id) {
            return view('pages.404', array_merge($settingArr, [
                'errCode' => '500',
                'message' => '没有文章 id'
            ]));
        }
        $res = \Illuminate\Support\Facades\DB::table('blog')
            ->orWhere(['id' => $id, 'url' => $id])->where(['is_del' => 0, 'site' => $request->siteId])->first();
        if (!$res) {
            return view('pages.404', array_merge($settingArr, [
                'errCode' => '404',
                'message' => '该文章不存在'
            ]));
        }

        $category = isset($res->category) ?
            \Illuminate\Support\Facades\DB::table('category')->where(['id' => $res->category])->first(['name'])->name ?? ''
            : '';
        $res->category_name = $category;
        $themeJson = json_decode($settings["theme_json_{$settings['theme']}"], true);
        $pageData = array_merge(
            $settingArr,
            [
                'post' => $res,
                'j' => $themeJson
            ]
        );
        if (Common::isMobile()) {
            return view('pages.post_mobile', $pageData);
        } else {
            return view('pages.post', $pageData);
        }
    }

    public function page($id, \Illuminate\Http\Request $request)
    {
        $settings = (new \App\Db\Setting())->getSettingDir($request->siteId);
        $settingArr = [
            'logo' => $settings['logo'],
            'title' => $settings['title'],
            'subTitle' => $settings['subTitle'],
            'nav' => json_decode($settings['nav']) ?? [],
            'footer' => $settings['footer']
        ];
        if (!$id) {
            return view('pages.404', array_merge($settingArr, [
                'errCode' => '500',
                'message' => '无页面 id'
            ]));
        }
        $res = \Illuminate\Support\Facades\DB::table('page')
            ->orWhere(['id' => $id, 'url' => $id])->where(['is_del' => 0, 'site' => $request->siteId])->first();
        if (!$res) {
            return view('pages.404', array_merge($settingArr, [
                'errCode' => '404',
                'message' => '该页面不存在'
            ]));
        }

        $res->category_name = '';
        $themeJson = json_decode($settings["theme_json_{$settings['theme']}"], true);

        $pageData = array_merge($settingArr, [
            'post' => $res,
            'j' => $themeJson
        ]);

        if (Common::isMobile()) {
            return view('pages.post_mobile', $pageData);
        } else {
            return view('pages.post', $pageData);
        }
    }

    public function category(\Illuminate\Http\Request $request)
    {
        $settings = (new \App\Db\Setting())->getSettingDir($request->siteId);
        $settingArr = [
            'logo' => $settings['logo'],
            'title' => $settings['title'],
            'subTitle' => $settings['subTitle'],
            'nav' => json_decode($settings['nav']) ?? [],
            'footer' => $settings['footer']
        ];
        $res = (new \App\Db\Columns())->getColumns(true, $request->siteId);

        return view('pages.category', array_merge($settingArr, [
            'categorys' => $res
        ]));
    }
}
